package com.tiyende.kash.loop.ui.presenter

import com.tiyende.kash.loop.common.CommonPresenter
import com.tiyende.kash.loop.configs.TiyendeApiPath
import com.tiyende.kash.loop.configs.TiyendeApiUrl
import com.tiyende.kash.loop.configs.TiyendeApiUrl.addCommonParams
import com.tiyende.kash.loop.request.IHttpCallback
import com.tiyende.kash.loop.ui.contract.IViewContract
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/21 13:46
 * @Annotation：认证流程 - 法语地区绑卡
 */
class TiyendeAuthenticationStepWalletPresenter(private val iView: IViewContract.ITiyendeAuthenticationStepWalletView): CommonPresenter(iView) {

    /**
     * 获取已绑定的账户列表
     */
    fun requestAuthStepWalletListAction() {
        iView.showTiyendeLoading()
        val httpUrl = TiyendeApiUrl.getTiyendeHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", TiyendeApiPath.TIYENDE_PATH.TIYENDE_API_ACCOUNT_LIST_FRENCH_PATH)
        }
        doHttpPostAction(httpUrl, params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val array = data.optJSONArray("obj")
                val accountList = arrayListOf<JSONObject>()

                if (array != null && array.length() > 0) {
                    for (i in 0..<array.length()) {
                        val item = array.optJSONObject(i)
                        item.put("isEdit", false)
                        accountList.add(item)
                    }
                }

                if (accountList.size < 2) {
                    for (i in 0..<2 - accountList.size) {
                        val item = JSONObject()
                        item.put("isEdit", true)
                        accountList.add(item)
                    }
                }
                iView.showTiyendeAuthenticationStepWalletList(accountList)
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                iView.hiddenTiyendeLoading()
            }
        })
    }

    /**
     * 删除账户
     */
    fun onDeleteAuthStepWalletAction(ids: String) {
        iView.showTiyendeLoading()
        val httpUrl = TiyendeApiUrl.getTiyendeHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", TiyendeApiPath.TIYENDE_PATH.TIYENDE_API_ACCOUNT_DELETE_PATH)
            put("ids", ids)
        }
        doHttpPostAction(httpUrl, params, object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                iView.showTiyendeToast(data.optString("msg"))
                //刷新列表
                requestAuthStepWalletListAction()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }
}